//
//  HSDSpidermanLocationHelper.m
//  AFNetworking
//
//  Created by 恒信博达 on 2018/3/23.
//

#import "HSDSpidermanLocationHelper.h"
#import <CoreLocation/CoreLocation.h>

@interface HSDSpidermanLocationHelper ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *manager;

@end

@implementation HSDSpidermanLocationHelper

- (instancetype)init {
    self = [super init];
    if (self) {
        _locationModel = [[HSDSpidermanLocationModel alloc] init];
        _locationModel.latitude = @"";
        _locationModel.longitude = @"";
    }
    return self;
}

- (void)startLocation {
    [self location];
}

- (void)location {
    if ([CLLocationManager locationServicesEnabled]) {
        // 有定位服务
        if (_manager) {
            [_manager startUpdatingLocation];
        } else {
            _manager = [[CLLocationManager alloc] init];
            //设置定位的精度
            [_manager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
            _manager.distanceFilter = 1000.0f;
            _manager.delegate = self;
            if ([[[UIDevice currentDevice] systemVersion] floatValue] > 8.0) {
                [_manager requestWhenInUseAuthorization];
            }
            [_manager startUpdatingLocation];
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation * newLoaction = locations[0];
    CLLocationCoordinate2D oCoordinate = newLoaction.coordinate;
    NSLock *l = [NSLock new];
    [l lock];
    _locationModel.latitude = [NSString stringWithFormat:@"%lf",oCoordinate.latitude];
    _locationModel.longitude = [NSString stringWithFormat:@"%lf",oCoordinate.longitude];
    [l unlock];
    [_manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [_manager startUpdatingLocation];
}

@end
